package com.xiaouyudeguang.common.expiration.config;

import com.xiaouyudeguang.common.config.CacheConfig;
import com.xiaouyudeguang.common.expiration.service.RedisExpirationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.List;

public class RedisExpirationConfig {

	private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

	@Autowired(required = false)
	public List<RedisExpirationService> redisExpirationServices;

	@Bean
	@ConditionalOnMissingBean
	public KeyExpirationEventMessageListener configKeyExpirationEventMessageListener(RedisMessageListenerContainer container) {
		return new KeyExpirationEventMessageListener(container) {
			@Override
			public void onMessage(Message message, byte[] pattern) {
				String expiredKey = message.toString();
//				logger.debug("过期的key.{}", expiredKey);
				if (redisExpirationServices == null || redisExpirationServices.isEmpty()) {
//					logger.debug("redisKeyExpirationServices is not exist");
					return;
				}
				redisExpirationServices.forEach(redisExpirationService -> {
					redisExpirationService.doProcess(expiredKey, pattern);
				});
			}
		};
	}
}